package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.TableManagerService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class TableManagerController {
	private static final Logger logger = LoggerFactory
			.getLogger(TableManagerController.class);

	@Autowired
	private TableManagerService tablemanagerservice;

	/**
	 * 得到表名一览信息
	 */
	@RequestMapping(value = "/getTableNameList")
	public void getTableNameList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {

		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");

		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("pageEnd", page.getStart() + page.getLimit());
				param.put("pageStart", page.getStart());
				ArrayList<HashMap<String, Object>> logs = tablemanagerservice
						.getTableNameList(param);
				if (logs != null && logs.size() > 0) {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 从系统表中获取所有表名
	 */
	@RequestMapping(value = "/getTableName")
	public void getTableName(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String, Object>> result = tablemanagerservice
					.getAllTableName();
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 添加表名
	 */
	@RequestMapping(value = "/tableManagerAdd", method = RequestMethod.POST)
	public void TableManagerAdd(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String t_name = (String) request.getParameter("t_name");
		String t_name_cn = (String) request.getParameter("t_name_cn");
		String t_name_en = (String) request.getParameter("t_name_en");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		String cpn_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				int userId = Integer.parseInt(user.getUserId());
				Date date = new Date();
				java.text.DateFormat format = new java.text.SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String time = format.format(date);
				param = new HashMap<String, Object>();
				param.put("cpn_id", cpn_id);
				param.put("t_name", t_name);
				param.put("t_name_cn", t_name_cn);
				param.put("t_name_en", t_name_en);
				param.put("create_user", userId);
				param.put("create_time", time);
				int ret;
				ret = tablemanagerservice.tableManagerAdd(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	// 删除表名
	@RequestMapping(value = "/tableManagerDelete", method = RequestMethod.POST)
	public void TableManagerDelete(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String t_name = (String) request.getParameter("t_name");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		response.setContentType("text/plain;charset=UTF-8");
		String[] t_namelist = t_name.split(",");
		String cpn_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		try {
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			boolean flag = false;
			int action = 0;
			for (int i = 0; i < t_namelist.length; i++) {
				flag = this.addTableNameHistory(t_namelist[i], cpn_id, user, action);
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("t_name", t_namelist[i]);
				list.add(map);
			}
			param.put("t_name", list);
			
			if(flag){
				int ret;
				ret = tablemanagerservice.tableManagerDelete(param);
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
				writer.print(JackJson.fromObjectToJson(result));
			}else{
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 修改表名
	 */
	@RequestMapping(value = "/tableManagerEdit", method = RequestMethod.POST)
	public void TableManagerEdit(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String t_name = (String) request.getParameter("t_name");
		String t_name_cn = (String) request.getParameter("t_name_cn");
		String t_name_en = (String) request.getParameter("t_name_en");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		String cpn_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				int userId = Integer.parseInt(user.getUserId());
				Date date = new Date();
				java.text.DateFormat format = new java.text.SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String time = format.format(date);
				param = new HashMap<String, Object>();
				param.put("t_name", t_name);
				param.put("t_name_cn", t_name_cn);
				param.put("t_name_en", t_name_en);
				param.put("create_user", userId);
				param.put("create_time", time);
				int action = 1;
				boolean flag = this.addTableNameHistory(t_name, cpn_id, user, action);
				if(flag){
					int ret;
					ret = tablemanagerservice.tableManagerEdit(param);
					if (ret == 0) {
						result.put("resultcode", 0);
					} else {
						result.put("resultcode", 9);
					}
					String returnMsg = JackJson.fromObjectToJson(result);
					logger.debug("{}", returnMsg);
					writer.print(returnMsg);
				}else{
					writer.print("");
				}
			} else {
				result.put("resultcode", 9);
			}
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 添加表名管理履历
	 * @param t_name 已添加的表名，根据此参数查询出要删除的数据
	 * @param user 当前用户，用来添加执行操作的用户id
	 * @param action 0为删除，1为修改
	 * @return
	 */
	private boolean addTableNameHistory(String t_name, String cpn_id, User user, int action) {
		try{
			HashMap<String,Object> history_param = new HashMap<String,Object>();
			
			history_param.put("cpn_id", cpn_id);
			history_param.put("t_name", t_name);
			history_param.put("action", action);
			history_param.put("user_id", user.getUserId());
			history_param.put("user_name", user.getAccount());
			history_param.put("update_time", Tools.getCurrentDay());
			tablemanagerservice.addTableNameHistory(history_param);
			return true;
		}catch(Exception e){
			return false;
		}
	}
}